package io.github.zeleven.mua.fraction;

import com.jcodecraeer.xrecyclerview.XRecyclerView;

import io.github.zeleven.mua.ResourceTable;
import io.github.zeleven.mua.SettingsFragment;
import io.github.zeleven.mua.adapter.ListContainerAdapter;
import io.github.zeleven.mua.bean.FileBean;
import io.github.zeleven.mua.bean.SliceCallBack;
import io.github.zeleven.mua.bean.StringCache;
import io.github.zeleven.mua.slice.EditAbilitySlice;
import io.github.zeleven.mua.utl.DialogUtil;
import io.github.zeleven.mua.utl.LogUtil;
import io.github.zeleven.mua.utl.PreferenceUtil;
import io.github.zeleven.mua.utl.ToastUtil;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.ability.fraction.Fraction;
import ohos.aafwk.content.Intent;
import ohos.agp.animation.Animator;
import ohos.agp.animation.AnimatorProperty;
import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;
import ohos.agp.components.DependentLayout;
import ohos.agp.components.DirectionalLayout;
import ohos.agp.components.DragInfo;
import ohos.agp.components.Image;
import ohos.agp.components.LayoutScatter;
import ohos.agp.components.ListContainer;
import ohos.agp.components.Text;
import ohos.agp.window.service.Display;
import ohos.agp.window.service.DisplayManager;
import ohos.app.Environment;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * MainFraction
 *
 * @since 2021-05-11
 */
public class MainFraction extends Fraction {
    private static final int THREE = 3;
    private static final int FOUR = 4;
    private static final int INT = 0x001234;
    private static final int INT_300 = 300;
    private static final int INT_900 = 900;
    private static final int INT_1500 = 1500;
    private HiLogLabel hiLogLabel = new HiLogLabel(HiLog.LOG_APP, INT, "zf------");
    private DependentLayout dependentLayout;
    private Display display;
    private AbilitySlice slice;
    private SliceCallBack callBack;
    private DirectionalLayout synchronization;
    private DirectionalLayout help;
    private DirectionalLayout setting;
    private XRecyclerView mListContainer;
    private ListContainerAdapter adapter;
    private Image image;
    private DirectionalLayout directionalLayout;
    private List<FileBean> cachelist = new ArrayList<>();
    private List<FileBean> list = new ArrayList<>();
    private DependentLayout empty;
    private Text emptyText;
    private Text describe;
    private Text synchronizationtext;
    private Text themetext;
    private Text helptext;
    private Text settingtext;
    private float mDownY;
    private boolean isAnimator = false;

    /**
     * MainFraction
     *
     * @param slice
     * @param callBack
     */
    public MainFraction(AbilitySlice slice, SliceCallBack callBack) {
        this.slice = slice;
        this.callBack = callBack;
    }

    /**
     * setText
     *
     * @param text
     */
    public void setText(String text) {
        list.clear();
        if (text.equals("") || text.isEmpty()) {
            list.addAll(cachelist);
        } else {
            for (FileBean fileBean : cachelist) {
                int b = fileBean.getTitle().indexOf(text);
                HiLog.info(hiLogLabel, "名称  " + b);
                if (b > -1) {
                    list.add(fileBean);
                }
            }
        }
        adapter.notifyDataChanged();
    }

    @Override
    protected Component onComponentAttached(LayoutScatter scatter, ComponentContainer container, Intent intent) {
        Component component = scatter.parse(ResourceTable.Layout_fragment_main, null, false);
        display = DisplayManager.getInstance().getDefaultDisplay(slice).get();
        synchronization = (DirectionalLayout) component.findComponentById(ResourceTable.Id_fragmeng_synchronization);
        help = (DirectionalLayout) component.findComponentById(ResourceTable.Id_help_main_fragment);
        mListContainer = (XRecyclerView) component.findComponentById(ResourceTable.Id_listContainer);
        directionalLayout = (DirectionalLayout) component.findComponentById(ResourceTable.Id_borderlayout);
        setting = (DirectionalLayout) component.findComponentById(ResourceTable.Id_setting_main_fragment);
        empty = (DependentLayout) component.findComponentById(ResourceTable.Id_empty_list);
        emptyText = (Text) component.findComponentById(ResourceTable.Id_empty_text);
        describe = (Text) component.findComponentById(ResourceTable.Id_describe);
        synchronizationtext = (Text) component.findComponentById(ResourceTable.Id_fragmeng_synchronization_text);
        themetext = (Text) component.findComponentById(ResourceTable.Id_theme_main_fragment_text);
        helptext = (Text) component.findComponentById(ResourceTable.Id_help_main_fragment_text);
        settingtext = (Text) component.findComponentById(ResourceTable.Id_setting_main_fragment_text);
        image = (Image) component.findComponentById(ResourceTable.Id_list_fraction_img);
        dependentLayout = (DependentLayout) component.findComponentById(ResourceTable.Id_slide_layout);
        dependentLayout.setWidth(display.getAttributes().width - display.getAttributes().width / FOUR);
        return component;
    }

    @Override
    protected void onActive() {
        super.onActive();
        cutLanguage();
    }

    /**
     * 适配语言
     */
    public void cutLanguage() {
        setCacheStatic(PreferenceUtil.getInstance().getInt("int", 0));
        if (StringCache.getInstance().getLanguageType() == StringCache.Default || StringCache.getInstance().getLanguageType() == StringCache.Chinese) {
            emptyText.setText(slice.getString(ResourceTable.String_create_file));
            describe.setText(slice.getString(ResourceTable.String_app_describe));
            synchronizationtext.setText(slice.getString(ResourceTable.String_drawer_item_sync));
            themetext.setText(slice.getString(ResourceTable.String_drawer_item_theme));
            helptext.setText(slice.getString(ResourceTable.String_drawer_item_help));
            settingtext.setText(slice.getString(ResourceTable.String_drawer_item_settings));
        } else if (StringCache.getInstance().getLanguageType() == StringCache.English) {
            describe.setText(slice.getString(ResourceTable.String_en_app_describe));
            emptyText.setText(slice.getString(ResourceTable.String_en_create_file));
            synchronizationtext.setText(slice.getString(ResourceTable.String_en_drawer_item_sync));
            themetext.setText(slice.getString(ResourceTable.String_en_drawer_item_theme));
            helptext.setText(slice.getString(ResourceTable.String_en_drawer_item_help));
            settingtext.setText(slice.getString(ResourceTable.String_en_drawer_item_settings));
        } else if (StringCache.getInstance().getLanguageType() == StringCache.Chinesefont) {
            String string = slice.getString(ResourceTable.String_tw_app_describe);
            describe.setText(string);
            String emptyString = slice.getString(ResourceTable.String_tw_create_file);
            emptyText.setText(emptyString);
            synchronizationtext.setText(slice.getString(ResourceTable.String_tw_drawer_item_sync));
            themetext.setText(slice.getString(ResourceTable.String_tw_drawer_item_theme));
            helptext.setText(slice.getString(ResourceTable.String_tw_drawer_item_help));
            settingtext.setText(slice.getString(ResourceTable.String_tw_drawer_item_settings));
        }
    }

    /**
     * static赋值
     *
     * @param anInt static int type
     */
    public static void setCacheStatic(final int anInt) {
        StringCache.getInstance().setLanguageType(anInt);
    }

    @Override
    protected void onStart(Intent intent) {
        super.onStart(intent);
        synchronization.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                DialogUtil.show(slice, "抱歉，暂时不支持同步", "确定");
            }
        });

        help.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                callBack.ClickType(THREE);
            }
        });
        setting.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                slice.present(new SettingsFragment(slice, new SliceCallBack() {
                    @Override
                    public void ClickType(int type) {
                    }
                }), new Intent());
            }
        });
        readFile();
        adapter = new ListContainerAdapter(list, slice);
        mListContainer.setItemProvider(adapter);
        mListContainer.setItemClickedListener(new ListContainer.ItemClickedListener() {
            @Override
            public void onItemClicked(ListContainer listContainer, Component component, int i, long l) {
                FileBean fileBean = list.get(i);
                slice.present(new EditAbilitySlice(), new Intent().setParam("content", fileBean));
                StringCache.getInstance().setFileName(fileBean.getTitle().replace(".md", ""));
            }
        });

        mListContainer.setDraggedListener(Component.DRAG_VERTICAL, new Component.DraggedListener() {
            @Override
            public void onDragDown(Component component, DragInfo dragInfo) {
                mDownY = dragInfo.downPoint.getPointY();
            }

            @Override
            public void onDragStart(Component component, DragInfo dragInfo) {
            }

            @Override
            public void onDragUpdate(Component component, DragInfo dragInfo) {
                if (mListContainer.getChildCount() > 0) {
                    float updatePointPointY = dragInfo.updatePoint.getPointY();
                    int firstItem = mListContainer.getFirstVisibleItemPosition();
                    Component componentAt = mListContainer.getComponentAt(firstItem);
                    if (componentAt.getTranslationY() == 0 && firstItem == 0 && !isAnimator) {
                        if (updatePointPointY > mDownY) {
                            directionalLayout.setVisibility(Component.VISIBLE);
                            float index = updatePointPointY - mDownY;
                            if (directionalLayout.getContentPositionY() < INT_300) {
                                directionalLayout.setContentPositionY(index);
                                image.setRotation(index);
                            }
                        }
                    }
                }
                if (isAnimator || directionalLayout.getVisibility() == Component.HIDE) {
                    mListContainer.scrollBy(0, (int) -dragInfo.yOffset);
                }
            }

            @Override
            public void onDragEnd(Component component, DragInfo dragInfo) {
                endAnimator();
            }

            @Override
            public void onDragCancel(Component component, DragInfo dragInfo) {
            }
        });
    }

    private void endAnimator() {
        if (directionalLayout.getVisibility() == Component.VISIBLE) {
            AnimatorProperty animatorProperty = image.createAnimatorProperty();
            animatorProperty.rotate(INT_900).setDuration(INT_1500)
                    .setStateChangedListener(new Animator.StateChangedListener() {
                        @Override
                        public void onStart(Animator animator) {
                            isAnimator = true;
                        }

                        @Override
                        public void onStop(Animator animator) {
                        }

                        @Override
                        public void onCancel(Animator animator) {
                        }

                        @Override
                        public void onEnd(Animator animator) {
                            directionalLayout.setVisibility(Component.HIDE);
                            directionalLayout.setContentPositionY(0);
                            isAnimator = false;
                            readFile();
                            ToastUtil.toast(slice, "" + list.size());
                        }

                        @Override
                        public void onPause(Animator animator) {
                        }

                        @Override
                        public void onResume(Animator animator) {
                        }
                    }).start();
        }
    }

    /**
     * readFile
     *
     */
    public void readFile() {
        cachelist.clear();
        list.clear();
        try {
            File file = slice.getApplicationContext().getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS);
            BufferedReader in = null;
            File[] files = file.listFiles();
            for (int i = files.length - 1; i > -1; i--) {
                StringBuffer sb = new StringBuffer();
                File files1 = files[i];
                String str = null;
                in = new BufferedReader(new FileReader(files1));
                while ((str = in.readLine()) != null) {
                    sb.append(str);
                }
                String s = sb.toString().replaceAll("___", "\n");
                HiLog.info(hiLogLabel, sb.toString());
                String name = files1.getName();
                FileBean fileBean = new FileBean(name, s);
                long millis = System.currentTimeMillis();
                long l = files1.lastModified();
                fileBean.setTime((int) (l - millis));
                list.add(fileBean);
            }
            Collections.sort(list);
            cachelist.addAll(list);
            if (list.size() > 0) {
                empty.setVisibility(Component.HIDE);
            } else {
                empty.setVisibility(Component.VISIBLE);
            }
        } catch (FileNotFoundException e) {
            HiLog.info(hiLogLabel, "FileNotFoundException   " + e.getMessage());
            e.printStackTrace();
        } catch (IOException e) {
            HiLog.info(hiLogLabel, "IOException    " + e.getMessage());
            e.printStackTrace();
        } finally {
            LogUtil.info(MainFraction.class.getName(),"finally");
        }
        if (adapter != null) {
            adapter.notifyDataChanged();
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
    }
}
